<template>
  <div style="padding: 20px 20px" class="step_line">
    <el-form
      :model="ruleFormHD"
      :rules="rulesHD"
      ref="ruleForm"
      label-width="100px"
      class="demo-form-inline inputForm"
      label-position="top"
      :disabled="disable"
      :key="ruleFormHD.type"
    >
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="回箱类型" prop="type">
            <el-select
              id="box_recycle_down"
              v-model="ruleFormHD.type"
              filterable
            >
              <el-option id="box_dispatch" key="2" label="回箱到干线" value="2"
                >回箱到干线</el-option
              >
              <el-option id="box_end" key="3" label="回箱到末端" value="3"
                >回箱到末端</el-option
              >
              <el-option id="box_firm" key="1" label="回箱到厂商" value="1"
                >回箱到厂商</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="ruleFormHD.type === '1'">
          <el-form-item
            label="厂商名称"
            prop="manufacturer"
            :rules="{
              required: true,
              message: '请填写厂商名称',
              trigger: 'blur',
            }"
          >
            <el-input
              id="firm_name"
              v-model="ruleFormHD.manufacturer"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="this.ruleFormHD.type === '1'">
          <el-form-item label="厂商地址" prop="receiver.address">
            <el-input
              id="firm_address"
              v-model="ruleFormHD.receiver.address"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发件网点" prop="from_network_id">
            <el-select
              id="from_network_down"
              v-model="ruleFormHD.from_network_id"
              filterable
              @change="
                (val) => handleChangeNetwork(val, 'sender', 'from_network_name')
              "
            >
              <el-option
                id="from_network"
                v-for="item in websiteData"
                :label="item.name"
                :value="item.id + ''"
                :key="item.id + ''"
                >{{ item.name }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发件地址" prop="sender.address">
            <el-input
              id="from_address"
              v-model="ruleFormHD.sender.address"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发件人" prop="sender.id">
            <el-select
              id="sender_down"
              v-model="ruleFormHD.sender.id"
              placeholder="请选择"
              @change="(val) => handleChangePerson(val, 'sender')"
              filterable
            >
              <el-option
                id="sender"
                v-for="item in senderData"
                :label="item.name"
                :value="item.id + ''"
                :key="item.id + ''"
                >{{ item.name }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发件人电话" prop="sender.phone">
            <el-input
              id="sender_phone"
              v-model="ruleFormHD.sender.phone"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col
          :span="6"
          v-if="this.ruleFormHD.type === '2' || this.ruleFormHD.type === '3'"
        >
          <el-form-item
            label="收件网点"
            prop="to_network_id"
            :rules="{
              required: true,
              message: '请选择收件网点',
              trigger: 'change',
            }"
          >
            <el-select
              id="to_network_down"
              v-model="ruleFormHD.to_network_id"
              filterable
              @change="
                (val) => handleChangeNetwork(val, 'receiver', 'to_network_name')
              "
            >
              <el-option
                id="to_network"
                v-for="item in websiteData"
                :label="item.name"
                :value="item.id + ''"
                :key="item.id + ''"
                >{{ item.name }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="6"
          v-if="this.ruleFormHD.type === '2' || this.ruleFormHD.type === '3'"
        >
          <el-form-item label="收件地址" prop="receiver.address">
            <el-input
              id="to_address"
              v-model="ruleFormHD.receiver.address"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="收件人"
            prop="receiver.id"
            :rules="{
              required:
                this.ruleFormHD.type === '2' || this.ruleFormHD.type === '3',
              message: '请选择收件人',
              trigger: 'change',
            }"
          >
            <el-select
              id="receiver_down"
              v-model="ruleFormHD.receiver.id"
              placeholder="请选择"
              @change="(val) => handleChangePerson(val, 'receiver')"
              filterable
            >
              <el-option
                id="receiver"
                v-for="item in senderData"
                :label="item.name"
                :value="item.id + ''"
                :key="item.id + ''"
                >{{ item.name }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收件人电话" prop="receiverPhone">
            <el-input
              id="receiver_phone"
              v-model="ruleFormHD.receiver.phone"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="运输类型" prop="carrier_type">
            <el-select
              id="carrier_type_down"
              v-model="ruleFormHD.carrier_type"
              @change="handleChangeCarrierType"
              filterable
              placeholder="请选择"
            >
              <el-option
                id="carrier_type"
                v-for="item in types"
                :label="item.value"
                :value="item.index"
                :key="item.index"
                >{{ item.value }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="ruleFormHD.carrier_type === '1'">
          <el-form-item label="快递公司"    :class="{
            'select-add': isHavePermission('company_driver_create'),
          }"  prop="express_id" >
            <el-select
              id="collect_company_down"
              v-model="ruleFormHD.express_id"
              @change="handleChangeCompany"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                id="collect_company"
                v-for="item in companyData"
                :label="item.name"
                :value="item.id + ''"
                :key="item.id"
                >{{ item.name }}</el-option
              >
            </el-select>
            <el-button
            v-permission="'company_carrier_create'"
            @click="handleAddMaterial('carrier')"
            class="add-right"
            >+</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="ruleFormHD.carrier_type === '1'">
          <el-form-item label="快递单号" prop="express_no">
            <el-input
              id="carrier_number"
              v-model="ruleFormHD.express_no"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="mode === 'detail' || mode === 'singleDetail'">
          <el-form-item label="回箱状态" prop="status">
            <el-select
              v-model="ruleFormHD.status"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in ['未签收', '已签收']"
                :label="item"
                :value="index + ''"
                :key="index"
                >{{ item }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="6" v-if="(mode === 'detail' || mode === 'singleDetail')">
          <el-form-item label="创建回箱时间" prop="update_time">
            <el-date-picker :value="ruleFormHD.create_time*1000" type="datetime" placeholder="创建回箱时间"
              value-format="timestamp">
            </el-date-picker>
          </el-form-item>
        </el-col> -->
        <el-col :span="6" v-if="mode === 'detail' || mode === 'singleDetail'">
          <el-form-item label="回箱干线签收时间" prop="ground_line_sign_time">
            <el-date-picker
              :value="ruleFormHD.ground_line_sign_time * 1000"
              type="datetime"
              placeholder="回箱干线签收时间"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col
          :span="6"
          v-if="
            ruleFormHD.status === '1' &&
            (mode === 'detail' || mode === 'singleDetail')
          "
        >
          <el-form-item label="回箱末端签收时间" prop="signTime">
            <el-date-picker
              v-model="signTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间" prop="create_time">
            <el-date-picker
              v-model="ruleFormHD.create_time"
              clearable
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
              :disabled="mode === 'edit' || mode === 'singleEdit'"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="mode === 'detail' || mode === 'singleDetail'">
          <el-form-item label="操作时间" prop="update_time">
            <el-date-picker
              :value="ruleFormHD.update_time * 1000"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="24"> 
                     <!--  -->
          <el-form-item label="回箱上传" ref="uploadReceipt" prop="images"
          :rules="{
            required: ruleFormHD.carrier_type==='1',
            message: '请上传回箱图片',
            trigger: 'change',
          }"
          >
            <el-upload
              action
              :auto-upload="false"
              list-type="picture-card"
              :before-remove="beforeRemove"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :file-list="fileList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" append-to-body>
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
      <el-table
        :data="ruleFormHD['waybill_items']"
        class="safari_table"
        v-if="ruleFormHD['waybill_items'].length"
        default-expand-all
        style="width: 80%"
        border
      >
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column type="expand">
          <template slot-scope="props">
            <!-- {{ props.row.incubator_info }} -->
            <el-table
              :data="props.row.incubator_list"
              style="width: 100%"
              border
            >
              <el-table-column width="50"> </el-table-column>
              <el-table-column label="回箱型号" prop="incubator_type" width="160">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row['incubator_type']"
                    placeholder="请选择"
                    filterable
                  >
                    <el-option
                      v-for="item in packageData"
                      :label="item.item_name"
                      :value="item.item_code"
                      :key="item.item_code"
                      >{{ item.item_name }}</el-option
                    >
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="保温箱编号" prop="incubator_no"  width="160">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row['incubator_no']"
                    placeholder="请选择"
                    disabled
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="回箱个数" prop="count">
                <template slot-scope="scope">
                  <!-- <el-input id="box_recycle_count" oninput="value=value.replace(/[^\d]/g,'')" @input="handleInputTotal" v-model="scope.row['count']"></el-input> -->
                  <el-form-item
                    style="margin-bottom: 1px"
                    :prop="
                      'waybill_items.' +
                      props.$index +
                      '.incubator_list.' +
                      scope.$index +
                      '.count'
                    "
                    :rules="rulesHD.count"
                  >
                    <el-input
                      id="box_recycle_count"
                      oninput="value=value.replace(/[^\d]/g,'')"
                      @input="handleInputTotal"
                      v-model="scope.row['count']"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="回箱费用"
                prop="expense"
                property="expense"
              >
                <!-- <template slot="header">
                  <span style="color: red">*</span> <span>费用</span>
                </template> -->
                <template slot-scope="scope">
                  <el-form-item
                    style="margin-bottom: 1px"
                    :prop="
                      'waybill_items.' +
                      props.$index +
                      '.incubator_list.' +
                      scope.$index +
                      '.expense'
                    "
                    :rules="rulesHD.expense"
                  >
                    <el-input
                      id="box_recycle_money"
                      oninput="value=value.replace(/[^\d^\.]/g,'')"
                      v-model="scope.row['expense']"
                      @input="handleInputTotal"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="运单号"  width="320">
          <template slot-scope="scope">
            {{ scope.row["waybill_no"] }}
          </template>
        </el-table-column>
        <el-table-column label="回箱总个数" prop="total_count">
          <template slot-scope="scope">
            {{ scope.row["total_count"] }}
          </template>
        </el-table-column>
        <el-table-column label="回箱总费用" prop="total_expense">
          <template slot-scope="scope">
            {{ scope.row["total_expense"] }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="回箱型号">
          <template slot-scope="scope">
            <el-select v-model="scope.row['incubator_type']" placeholder="请选择" filterable>
              <el-option v-for="item in packageData" :label="item.item_name" :value="item.item_code"
                :key="item.item_code">{{ item.item_name }}</el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="回箱标签号">
          <template slot-scope="scope">
            <el-input v-model="scope.row['incubator_label']"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="回箱个数" prop="count" property="count">
          <template slot="header">
            <span style="color: red">*</span> <span>回箱个数</span>
          </template>
          <template slot-scope="scope">
            <el-form-item style="margin-bottom:1px;" :prop="'waybill_items.' + scope.$index + '.count'"
              :rules="rulesHD.count">
              <el-input oninput="value=value.replace(/[^\d]/g,'')" v-model="scope.row['count']"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="费用" prop="expense" property="expense">
          <template slot="header">
            <span style="color: red">*</span> <span>费用</span>
          </template>
          <template slot-scope="scope">
            <el-form-item style="margin-bottom:1px;" :prop="'waybill_items.' + scope.$index + '.expense'"
              :rules="rulesHD.expense">
              <el-input oninput="value=value.replace(/[^\d^\.]/g,'')" v-model="scope.row['expense']"></el-input>
            </el-form-item>
          </template>
        </el-table-column> -->
      </el-table>
      <div
        style="margin-top: 20px; text-align: right; padding-bottom: 20px"
        v-if="!disable"
      >
        <el-button id="create_cancel" @click="cancelFn">取消</el-button>
        <el-button
          id="create_ok"
          type="primary"
          v-preventReClick
          data-tracker="P4-6"
          @click="handleClickSubmit"
          :loading="submitLoading"
          >保存</el-button
        >
      </div>
    </el-form>
    <div>
      <notify
        v-if="notifyType"
        :noTifyData="noTifyData"
        :key="noTifyData.node_id"
      ></notify>
    </div>
    <CostControl :showDialog="costDialogShow"  :overWarning="overWarning" :tableData="cost_overruns_info" @ok="handleCostOk" @close="costDialogShow=false"></CostControl>
    <MaterialAdd
    :type="materialType"
    @ok="handleMaterialAddOk"
    @close="handleCloseMaterialDialog"
    :dialogVisible="materialDialogVisible"
    :diaremark="5"
  >
  </MaterialAdd>
  </div>
</template>
<script>
import {
  RecycleCreateFn,
  RecycleUpdateFn,
  getConsignorList,
  reqWebsiteList,
  RecycleDetailFn,
  getWaybillListFn,
  userList,
  carrierBox,
  RecycleWaybillBoxFn,
} from "@/api/waybill";
import { uploading } from "../../../material/common/common";
import { dictionanryList } from "@/page/material/common/common";
import { parseFen, parseYuan, commonAdd } from "@/utils/mUtils";
import { reqStaffList } from "@/api/report";
import { timestamp10 } from "@/utils/mUtils";
import notify from "@/components/notify/notify.vue"; // 时间转化
import CostControl from "../costControl.vue";
import MaterialAdd from "@/page/waybill/components/materialAdd.vue";
import { MATERIAL } from "@/page/waybill/constants";
import { isHavePermission } from "@/utils/mUtils";
export default {
  name: "recycle",
  data() {
    return {
      submitLoading: false,
      ruleFormHD: {
        type: "",
        waybill_items: [],
        sender: {
          id: "",
          name: "",
          phone: "",
          address: "",
        },
        receiver: {
          id: "",
          name: "",
          phone: "",
          address: "",
        },

        images: [],
        from_network_id: "",
        from_network_name: "",
        to_network_id: "",
        to_network_name: "",
        express_id: "",
        express_name: "",
        express_no: "",
        create_time: "", //创建时间
      },
      rulesHD: {
        type: [{ required: true, message: "请选择回箱类型", trigger: "blur" }],
        from_network_id: [
          { required: true, message: "请选择发件网点", trigger: "blur" },
        ],
        "sender.id": [
          { required: true, message: "请选择发件人", trigger: "change" },
        ],
        express_no: [
          { required: true, message: "请输入快递单号", trigger: "blur" },
        ],
        express_id: [
          { required: true, message: "请选择快递公司", trigger: "change" },
        ],
        carrier_type: [
          { required: true, message: "请选择运输类型", trigger: "change" },
        ],
        // expense: [
        //   { required: true, message: "请填写费用", trigger: "blur" },
        // ],
        count: [
          { required: true, message: "请填写回箱个数", trigger: "blur" },
          // {
          //   validator: this.checkCount,
          //   trigger: "blur",
          // },
        ],
      },
      senderData: [],
      receiverData: [],
      websiteData: [],
      fileList: [], //上传的文件
      dialogImageUrl: "",
      dialogVisible: false,
      websiteList: [],
      formData: {},
      packageData: [],
      signTime: "",
      companyData: [],
      types: [
        {
          index: "0",
          value: "自营",
        },
        {
          index: "1",
          value: "委外",
        },
      ],
      notifyType: false,
      noTifyData: {
        customer_id: "",
        product_type_id: "",
        node_id: "",
      },
      overWarning:"",
      cost_overruns_info:[
        ],//成本超出信息
      costDialogShow:false,
      materialDialogVisible:false,
      materialType: "",
      MATERIAL: MATERIAL,
    };
  },
  props: ["mode", "id", "ids", "isRecycleEnd", "recycleId", "waybillInfo"],
  components: { notify, CostControl,MaterialAdd },
  computed: {
    disable: function () {
      return this.mode === "detail" || this.mode === "singleDetail";
    },
  },
  watch: {
    id: {
      handler: function (val) {
        val && this.getDetail();
      },
      immediate: true,
    },
    "ruleFormHD.images": function (val) {
      this.$refs.uploadReceipt.clearValidate();
    },
  },
  mounted() {
    this.NotificationObj();
    if (this.mode === "edit" || this.mode === "detail") {
      this.getDetail();
    } else if (this.mode === "add") {
      this.initWaybillData();
      this.ruleFormHD.from_network_id = this.$store.state.user.branch_id + "";
      this.ruleFormHD.sender.id = this.$store.state.user.user_id + "";
      this.ruleFormHD.create_time = Date.now();

      this.handleChangeNetwork(
        this.ruleFormHD.from_network_id,
        "sender",
        "from_network_name"
      );
      this.handleChangePerson(this.ruleFormHD.sender.id, "sender");
    }
    // this.getWebsiteList();
    dictionanryList(["Package_model"]).then((res) => {
      this.packageData = res.data.list["Package_model"];
    });
    userList().then((res) => {
      const data = res.data || [];
      this.senderData = data.map((item) => {
        item.name = item.nickname;
        return item;
      });
      if (this.mode === "add") {
        this.ruleFormHD.sender.id = this.$store.state.user.user_id + "";
        this.handleChangePerson(this.ruleFormHD.sender.id, "sender");
      }
    });
    reqWebsiteList({}).then((res) => {
      this.websiteData = res.data;
      if (this.mode === "add") {
        this.ruleFormHD.from_network_id = this.$store.state.user.branch_id + "";
        this.handleChangeNetwork(
          this.ruleFormHD.from_network_id,
          "sender",
          "from_network_name"
        );
      }
    });
    carrierBox().then((res) => {
      this.companyData = res.data;
    });
  },
  methods: {
    getDetail() {
      RecycleDetailFn({
        id: this.id + "",
      }).then((result) => {
        if(!result.data) return;
        this.formatData(result.data);
        this.$emit('transmit', result.data.type)
      });
    },
    handleCostOk(cost_overruns_info){
      this.ruleFormHD.waybill_cost_overruns_info=cost_overruns_info;
      this.handleClickSubmit()
    },
    judgeOver(res){
      if(res.data.warning){
        this.costDialogShow=true;
        this.overWarning=res.data.warning;
        this.cost_overruns_info=res.data.cost_overruns_info||[];
        this.submitLoading = false;
        return true;
      }
      return false
    },
    handleClickSubmit() {
      // if (this.ruleFormHD.status === '1' && (this.mode === 'edit' || this.mode === 'singleEdit')) {
      //   this.$message({
      //     message: "回箱已签收，不能修改！",
      //     type: "warning",
      //   });
      //   return;
      // }
      this.$refs["ruleForm"].validate((valid) => {
        if (!valid) return;
        this.submitLoading = true;
        this.ruleFormHD.images = this.ruleFormHD.images.map((item) => item.url);
        // 回箱到厂商需要特殊处理 收件网点默认成发件网点
        if (this.ruleFormHD.type === "1") {
          this.ruleFormHD.to_network_id = this.ruleFormHD.from_network_id;
          this.ruleFormHD.to_network_name = this.ruleFormHD.from_network_name;
        }
        const _ruleForm = {
          ...this.ruleFormHD,
          waybill_items: JSON.parse(
            JSON.stringify(this.ruleFormHD.waybill_items)
          ),
          create_time: timestamp10(this.ruleFormHD.create_time),
        };
        _ruleForm.waybill_items.forEach((item) => {
          item.expense = parseFen(item.expense);
        });

        if (this.mode === "add") {
          RecycleCreateFn(_ruleForm).then((res) => {
            if (res && res.code === 10000) {
              if(this.judgeOver(res)) return;

              this.$message({
                message: "创建成功",
                type: "success",
              });
              this.$emit("update");
              this.$emit("updateFinish");
              this.submitLoading = false;
            } else {
              this.submitLoading = false;
              this.$message({
                message: res.message,
                type: "error",
              });
            }
          });
        } else {
          RecycleUpdateFn(_ruleForm).then((res) => {
            if (res && res.code === 10000) {
              if(this.judgeOver(res)) return;

              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.$emit("update");
              this.$emit("updateFinish");
              this.submitLoading = false;
            } else {
              this.submitLoading = false;
              this.$message({
                message: res.message,
                type: "error",
              });
            }
          });
        }
      });
    },
    handleChangeCompany(val) {
      const item = this.companyData.find((item) => item.id === Number(val));
      if (item) {
        this.ruleFormHD["express_name"] = item.name;
      }
    },
    handleClose() {
      this.$emit("parentAbnormalShow", false);
    },
    handleInputTotal() {
      this.handleTotal(this.ruleFormHD["waybill_items"]);
    },
    handleTotal(array = []) {
      array.forEach((item) => {
        item.total_count =
          item.incubator_list &&
          item.incubator_list.reduce((prev, next) => {
            return commonAdd(prev, next.count * 1);
          }, 0);
        item.total_expense =
          item.incubator_list &&
          item.incubator_list.reduce((prev, next) => {
            return commonAdd(prev, next.expense * 1);
          }, 0);
      });
    },
    handleSelectionChange() {},
    formatData(formData) {
      this.ruleFormHD = formData;
      const {
        images,
        sender_id,
        sender_name,
        sender_phone,
        sender_address,
        receiver_id,
        receiver_name,
        receiver_phone,
        receiver_address,
        incubator_type,
        incubator_label,
        waybill_id,
        incubator_list,
      } = formData;
      this.$set(this.ruleFormHD, "sender", {
        id: sender_id,
        name: sender_name,
        phone: sender_phone,
        address: sender_address,
      });
      this.$set(this.ruleFormHD, "receiver", {
        id: receiver_id,
        name: receiver_name,
        phone: receiver_phone,
        address: receiver_address,
      });
      const waybill_items = [
        {
          waybill_id,
          waybill_no: formData.waybill_no,
          // incubator_type: incubator_type === "0" ? "" : incubator_type,
          // incubator_label,
          // expense: parseYuan(formData.expense),
          // count: formData.count,
          incubator_list,
        },
      ];
      this.handleTotal(waybill_items);
      this.ruleFormHD["waybill_items"] = waybill_items;
      this.fileList = images.map((url) => {
        return {
          url,
        };
      });
      this.ruleFormHD.images = [...this.fileList];
      this.signTime = formData.sign_time * 1000;
      this.ruleFormHD.create_time = formData.create_time * 1000;
    },
    //取消函数方法
    cancelFn() {
      this.$emit("update");
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    //确定按钮函数
    async determineFn() {
      let { ruleFormHD } = this;
      let result = await RecycleUpdateFn(ruleFormHD);
    },
    // 图片上传功能
    handleChange(file, fileList, type) {
      this.fileList = fileList;
      var filelist = file.raw; //文件
      var filename = file.raw.uid + file.raw.name; //通过 uid和name组成文件的名字
      uploading(filelist, filename, type).then((res) => {
        this.ruleFormHD.images.push({
          uid: file.uid,
          url: res.res.requestUrls[0],
        });
      });
    },
    handleRemove(file, fileList) {
      const index = this.ruleFormHD.images.findIndex(
        (item) => item.uid === file.uid
      );
      index > -1 && this.ruleFormHD.images.splice(index, 1);
    },
    removeChange(file, fileList, type) {},
    handlePreview(file) {
      // this.dialogImageUrl = file.url;
      // this.dialogVisible = true;
      const regex = /\.(jpg|png|webp|jpeg)$/i;
      if (regex.test(file.url)||file.url.indexOf('blob:')==0) {
        this.$viewerApi({
          images: [file.url],
        });
      } else {
        window.open(file.url);
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // async getWebsiteList() {
    //   let result = await reqWebsiteList({ type: "0" });
    //   this.websiteList = result.data;
    // },
    handleChangeCarrierType(val) {
      // 选择自营后清快递公司和快递单号数据
      if (val === "0") {
        this.ruleFormHD.express_id = "";
        this.ruleFormHD.express_name = "";
        this.ruleFormHD.express_no = "";
      } else if (val === "1") {
        this.ruleFormHD.express_id = "";
      }
    },
    handleChangePerson(val, type) {
      if (val) {
        const selected = this.senderData.find(
          (item) => item.id === Number(val)
        );
        if (selected) {
          this.ruleFormHD[type].id = String(selected.id);
          this.ruleFormHD[type].name = selected.name;
          this.ruleFormHD[type].phone = selected.mobile;
        }
      } else {
        this.ruleFormHD[type] = {};
      }
    },
    handleChangeNetwork(val, type, key) {
      if (val) {
        const selected = this.websiteData.find(
          (item) => item.id === Number(val)
        );
        if (selected) {
          this.ruleFormHD[key] = selected.name;
          this.ruleFormHD[type].address = selected.address;
        }
      }
    },
    initWaybillData() {
      let { ids = "[]" } = this.$route.query || {};
      ids = JSON.parse(ids);
      const _ids = this.ids || ids.map(Number);

      RecycleWaybillBoxFn({ waybill_ids: _ids }).then((res) => {
        const data = res.data || [];
        // 没有待回箱数据的
        const emptyRecycle = data.filter((item) => item.incubator_list == null);
        // 有待回箱数据
        const hasRecycle = data.filter((item) => item.incubator_list);
        this.handleTotal(hasRecycle);
        if (emptyRecycle.length > 0) {
          const emptyWaybillNos = emptyRecycle
            .map((item) => `${item.waybill_no}-${item.remark}`)
            .join("<br/>");
          this.$alert(emptyWaybillNos, "提示", {
            confirmButtonText: "确定",
            dangerouslyUseHTMLString: true,
            callback: (action) => {},
          });
        }
        this.ruleFormHD["waybill_items"] = hasRecycle;
        this.$forceUpdate();
      });
      // getWaybillListFn({ ids: _ids }).then((res) => {
      //   const list = [];
      //   res.data.data.forEach((item) => {
      //     const {
      //       id,
      //       sender_name,
      //       fromRegion_name,
      //       waybill_no,
      //       goods = [],
      //     } = item;
      //     list.push({
      //       waybill_id: id,
      //       waybill_no,
      //     });
      //   });
      //   this.ruleFormHD["waybill_items"] = list;
      //   this.$forceUpdate();
      // });
    },
    //Notification 通知事件
    NotificationObj() {
      // console.log("函数调用");
      // 数据改变
      (this.noTifyData = {
        customer_id: this.waybillInfo.customer_id + "",
        product_type_id: this.waybillInfo.waybill_product_type,
        node_id: "7", //回箱子
      }),
        (this.notifyType = true);
    },
    checkCount(rule, value, callback) {
      const reg = /^[1-9]\d*$/; // 正则表达式：大于0的数字
      if (reg.test(value)) {
        callback();
      } else {
        this.$message.warning("回箱个数必须大于0个");
      }
    },
    handleAddMaterial(materialType) {
      this.materialType = materialType;
      this.materialDialogVisible = true;
    },
    handleMaterialAddOk() {
      const { MATERIAL } = this;
     if (this.materialType === MATERIAL.CARRIER) {
        this.getCarrierBox();
      }
    },
    getCarrierBox() {
      carrierBox().then((res) => {
        this.companyData = res.data;
      });
    },
    handleCloseMaterialDialog() {
      this.materialDialogVisible = false;
    },
    isHavePermission(val) {
      return isHavePermission(val);
    },
  },
};
</script>
